﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Lacrima.Framework.Infrastructure
{
    public static partial class StringHelper
    {
        /// <summary>
        /// 使用字符串作为字符串的分割依据
        /// </summary>
        /// <param name="str"></param>
        /// <param name="target"></param>
        /// <param name="option"></param>
        /// <returns></returns>
        public static string[] SplitByString(this string str, string target, RegexOptions option = RegexOptions.IgnoreCase)
        {
            return Regex.Split(str, target, option);
        }

        /// <summary>
        /// 字符串翻转
        /// </summary>
        /// <param name="str">目标字符串</param>
        /// <returns>字符串翻转结果</returns>
        public static string Reverse(this string str)
        {
            if(string.IsNullOrWhiteSpace(str))
            {
                return str;
            }
            else
            {       
                return string.Join(string.Empty, str.ToCharArray().Reverse());
            }
        }

        /// <summary>
        /// 返回目标字符串在源字符串中的索引序列
        /// </summary>
        /// <param name="source">源字符串</param>
        /// <param name="target">目标字符串</param>
        /// <returns>目标字符串在源字符串中的索引序列</returns>
        public static int[] IndexArrayOf(this string source, string target)
        {
            if (source.IndexOf(target) >= 0)
            {
                string[] splitArray = source.SplitByString(target, RegexOptions.None);
                int[] indexArray = new int[splitArray.Length - 1];
                StringBuilder buffer = new StringBuilder();
                for (int i = 1; i < splitArray.Length; ++i)
                {
                    buffer.Append(splitArray[i - 1]);
                    indexArray[i - 1] = buffer.ToString().Length;
                    buffer.Append(target);
                }

                return indexArray;
            }
            else
                return null;
        }

    }
}
